package com.cy.hui_jie_dan.AutoFillAspert;


import com.cy.hui_jie_dan.AutoFill.AutoFill;
import com.cy.hui_jie_dan.comon.constant.AutoFillConstant;
import com.cy.hui_jie_dan.comon.context.BaseContext;
import com.cy.hui_jie_dan.comon.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspert {
    //切入点
    @Pointcut("execution(* com.cy.hui_jie_dan.mapper.*.*(..)) && @annotation(com.cy.hui_jie_dan.AutoFill.AutoFill)")
    public void autoFillPointCut(){
    }
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        //获取方法
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();
        //获取参数实体对象
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length==0){
            return;
        }
        Object arg = args[0];
        LocalDateTime now = LocalDateTime.now();
        if (value == OperationType.INSERT){
            try {
                log.info("开始填充");
                Method created_at = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method updated_at = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                updated_at.invoke(arg,now);
                created_at.invoke(arg,now);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else if(value == OperationType.UPDATE){
            try {
                Method updated_at = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                updated_at.invoke(arg,now);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


}
